import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: () => void) {
    const code = res.statusCode; // 响应状态码
    next();
    const logFormat = `
      Method: ${req.method} \t
      请求地址: ${req.originalUrl} \t
      IP: ${req.ip} \t
      code: ${code} \t
      params: ${JSON.stringify(req.params)}
      Query: ${JSON.stringify(req.query)}
      Body: ${JSON.stringify(req.body)} \t`;
    if (code >= 500) {
      Logger.error(logFormat, '中间件Middleware');
    } else if (code >= 400) {
      Logger.warn(logFormat, '中间件Middleware');
    } else {
      Logger.log(logFormat, '中间件Middleware');
    }
  }
}
